package com.zhkj.txg.module.home.vm

import android.app.Application
import androidx.lifecycle.MutableLiveData
import com.zhkj.lib.base.BaseViewModel
import com.zhkj.lib.base.UploadEntity
import com.zhkj.lib.base.UploadResponse
import com.zhkj.lib.http.BaseResponse
import com.zhkj.lib.http.HttpResponse
import com.zhkj.lib.http.ViewModelSubscribeListener
import com.zhkj.txg.module.home.model.HomeManager

class MerchantViewModel(application: Application) : BaseViewModel(application) {
    private val homeManager = HomeManager()
    val uploadLiveData = MutableLiveData<HttpResponse<UploadResponse>>()
    val registerLiveData = MutableLiveData<HttpResponse<BaseResponse>>()

    val licenseEntity = UploadEntity() // 营业执照图片数据
    val identifyFrontEntity = UploadEntity() // 身份证正面图片数据
    val identifyBackEntity = UploadEntity() // 身份证背面图片数据
    var gender: Int = 1 // 性别 1男 2女

    fun merchantRegister(token: String, name: String, age: String, mobile: String, reason: String) {
        uploadImage(0, licenseEntity, token, name, age, mobile, reason)
    }

    private fun uploadImage(
        index: Int,
        entity: UploadEntity,
        token: String, name: String, age: String, mobile: String, reason: String
    ) {
        val listener = object : ViewModelSubscribeListener<UploadResponse>(uploadLiveData) {
            override fun onSuccess(resp: UploadResponse) {
                super.onSuccess(resp)
                when (index) {
                    0 -> {
                        licenseEntity.url = resp.data?.url ?: ""
                        uploadImage(1, identifyFrontEntity, token, name, age, mobile, reason)
                    }
                    1 -> {
                        identifyFrontEntity.url = resp.data?.url ?: ""
                        uploadImage(2, identifyBackEntity, token, name, age, mobile, reason)
                    }
                    2 -> {
                        identifyBackEntity.url = resp.data?.url ?: ""
                        register(token, name, age, mobile, reason)
                    }
                }
            }
        }
        val picture = homeManager.uploadPicture(entity.filePath ?: "", listener)
        dispose.add(picture)
    }

    private fun register(token: String, name: String, age: String, mobile: String, reason: String) {
        val merchantRegister = homeManager.merchantRegister(
            token, name, gender, age, mobile, reason,
            licenseEntity.url, identifyFrontEntity.url, identifyBackEntity.url,
            ViewModelSubscribeListener(registerLiveData)
        )
        dispose.add(merchantRegister)
    }
}